package com.cjl.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cjl.auth.service.SysMenuService;
import com.cjl.auth.service.SysUserService;
import com.cjl.commons.exception.OAException;
import com.cjl.commons.jwt.JwtHelper;
import com.cjl.commons.result.Result;
import com.cjl.commons.utils.MD5;
import com.cjl.model.system.SysUser;
import com.cjl.vo.system.LoginVo;
import com.cjl.vo.system.RouterVo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "后台登录管理")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;

    //login
    @PostMapping("login")
    public Result login(@RequestBody LoginVo loginVo) {
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, username);
        SysUser sysUser = sysUserService.getOne(wrapper);

        if(sysUser == null){
            throw new OAException(2001, "用户不存在");
        }
        if (sysUser.equals(MD5.encrypt(password))) {
            throw new OAException(2001, "密码错误");
        }

        //如果被封禁
        if(sysUser.getStatus() == 0){
            throw new OAException(2001, "用户被封禁");
        }

        String token = JwtHelper.createToken(sysUser.getId(), sysUser.getUsername());
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        return Result.ok(map);
    }

    @GetMapping("info")
    public Result info(HttpServletRequest request){
        //从请求头获取用户信息
        String token = request.getHeader("token");
        Long userId = JwtHelper.getUserId(token);

        SysUser sysUser = sysUserService.getById(userId);

        List<RouterVo> routerList = sysMenuService.findUserMenuListByUserId(userId);

        List<String> permissionList = sysMenuService.findUserPermissionByUserId(userId);

        Map<String, Object> map = new HashMap<>();
        map.put("roles","[admin]");
        map.put("name", sysUser.getName());
        map.put("avatar","https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
        //返回用户可以操作的菜单
        map.put("routers", routerList);
        //返回用户可以操作的按钮
        map.put("buttons", permissionList);
        return Result.ok(map);
    }

    @PostMapping("logout")
    public Result logout(){
        return Result.ok();
    }
}
